package com.cole.gx095.service.impl;

import com.cole.gx095.Repository.SalecontractRepository;
import com.cole.gx095.domain.PurQuery;
import com.cole.gx095.service.SaleConService;
import com.cole.gx095.entity.Salecontract;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Service

public class SaleConServiceImpl implements SaleConService {

    @Autowired
    SalecontractRepository salecontractRepository;
    @Override
    public Page<Salecontract> findAllBy(PurQuery purQuery, Integer currentPage, Integer pageSize) {
        currentPage--;
        currentPage = currentPage < 0 ? 0 : currentPage;//page 为页码，数据库从0页开始
        //可以使用重载的 of(int page, int size, Sort sort) 方法指定排序字段
        Pageable pageable = PageRequest.of(currentPage, pageSize);

        Specification<Salecontract> purspecification = new Specification<Salecontract>() {
            @Override
            public Predicate toPredicate(Root<Salecontract> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();

                if (purQuery.getContractNum()!=null&&purQuery.getContractNum()!="")
                    predicateList.add(criteriaBuilder.equal(root.get("contractNum").as(String.class),purQuery.getContractNum()));
                if (purQuery.getContractDate()!=null)
                    predicateList.add(criteriaBuilder.equal(root.get("contractDate").as(Date.class),purQuery.getContractDate()));
                if (purQuery.getBuyUnit()!=null&&!"".equals(purQuery.getBuyUnit()))
                    predicateList.add(criteriaBuilder.equal(root.get("buyUnit").as(String.class),purQuery.getBuyUnit()));
                if (purQuery.getBillStatus()!=null)
                    predicateList.add(criteriaBuilder.equal(root.get("billStatus").as(Integer.class),purQuery.getBillStatus()));
                if (purQuery.getRemarks()!=null&&!"".equals(purQuery.getRemarks()))
                    predicateList.add(criteriaBuilder.equal(root.get("remarks").as(String.class),purQuery.getRemarks()));


                Predicate[] predicates = new Predicate[predicateList.size()];
                return query.where(predicateList.toArray(predicates)).getRestriction();
            }
        };
        return salecontractRepository.findAll(purspecification,pageable);//无数据时返回空列表;
    }

}
